Wrapping Webview JSBridge Interfaces
Our company’s existing JSBridge solution had cumbersome invocations, deeply nested parameters, and compatibility issues across multiple apps, drawing widespread complaints from our frontend developers…
Background
The client-side developers designed a JSBridge interaction scheme from their own perspective, based on the features that the frontend needed. While the scheme could effectively handle mutual function calls between native and H5 pages, it was difficult to promote because it didn’t adequately consider frontend developers’ usage habits. As a member of the frontend team assigned to the shared infrastructure group, I felt it was necessary to wrap a developer-friendly API layer on top of the existing solution.
Comparing Old and New Approaches
The Old Way
- Synchronous interface
1 | const data = { |
- Asynchronous interface
1 | const data = { |
Pros and Cons
Pros: 1. All interfaces use the unified
bridge.sendmethodCons: 1. Parameters are in multi-level JSON format, which is cumbersome; 2. Too many parameters make it easy to make mistakes; 3. Insufficient semantic clarity makes calls unintuitive
Example: closeWebView
Closes the current webview and passes a message to the next opened webview
1 | //sending parameters |
The New Way
- Synchronous
1 |
|
- Asynchronous
1 | jsbridge.isLogin() |
Pros and Cons
- Pros: 1. Implemented with Promises, matching frontend conventions; 2. Synchronous interfaces also return Promises for easy future async conversion; 3. API method names directly reflect the action, making them intuitive; 4. The catch function handles exceptions
The New Implementation
- Native and H5 interaction
H5 sends messages to native using the following function:
1 |
|
APIs without callbacks: directly use the above function to send messages to native
APIs with callbacks: in addition to sending the message, a unique ID is sent to identify the callback function. When the client finishes execution, it can use the unique ID to invoke the callback, with a timeout cleanup mechanism
- Dynamic API generation
Through an action list, corresponding API functions are generated, making it easy to dynamically scan for new APIs and add them to the JSBridge library
1 | // action list |
About the Generator Function
With functional programming gaining popularity, this function is essentially a curried function in the traditional sense:
- It accepts a function
- Returns a function that takes a single parameter
A higher-order function indeed!
Wrapping Webview JSBridge Interfaces
http://quanru.github.io/2016/10/02/Wrapping Webview JSBridge Interfaces

